package com.soul.server.server;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.soul.commons.exception.SoulGlobalException;
import com.soul.dubbo.api.db.UserInfoApi;
import com.soul.dubbo.api.mongo.PeachblossomApi;
import com.soul.model.db.UserInfo;
import com.soul.model.mongo.Peachblossom;
import com.soul.model.vo.ErrorResult;
import com.soul.model.vo.PageResult;
import com.soul.model.vo.PeachblossomVo;
import com.soul.server.exception.BusinessException;
import com.soul.server.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@Service
public class PeachblossomService {


    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference
    private PeachblossomApi peachblossomApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 桃花传音-发送语音
     *
     * @param soundFile 文件
     * @return null
     */
    public Integer sendPeachblossom(MultipartFile soundFile) {
        try {
            // 1. 获取当前用户id(语音发布者用户id)
            Long currendUserId = UserHolder.getUserId();
            // 1.2 获取redis中桃花传音次数  到达3次数则让用户充值   一条3次
            String peachblossomKey = "PEACHBLOSSOM_HASHKEY_" + currendUserId;
            String peachblossomCount = stringRedisTemplate.opsForValue().get(peachblossomKey);
            Integer num = 0;
            if (StringUtils.isNotEmpty(peachblossomCount)){
                num = Integer.valueOf(peachblossomCount);
                if (num >= 3 || num <= 0){
                    throw new SoulGlobalException("桃花传音次数达3次，请明天继续使用！");
                }
            }
            // 2. 构造发语音参数
            Peachblossom peachblossom = new Peachblossom();
            peachblossom.setUserId(currendUserId);
            // 3. 原文件名称处理后，拿到文件的后缀名称
            String filename = soundFile.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            // 4. 存储语音文件到fast服务器中
            StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
            // 5. 获取fstdfs服务器中语音文件路径URL
            String webServerUrl = fdfsWebServer.getWebServerUrl();
            peachblossom.setSoundFileUrl(webServerUrl + storePath.getFullPath());
            // 6. 调用服务保存语音文件 返回桃花传音次数
            Integer remainingTimes = peachblossomApi.addPeachblossom(peachblossom);
            // 7. redis存储计数桃花传音次数
            ++num;
            stringRedisTemplate.opsForValue().set(peachblossomKey,String.valueOf(num),1, TimeUnit.DAYS);
            // 8. 返回桃花传音剩余次数
            return getRemainingTimes(remainingTimes);
        } catch (IOException e) {
            throw new SoulGlobalException(ErrorResult.error());
        }
    }

    /**
     *  计算返回剩余桃花次数
     * @param count
     * @return
     */
    private Integer getRemainingTimes(Integer count) {
        if (count == 1){
            return 2;
        } else if (count == 2){
            return 1;
        }
        return 0;
    }

    /**
     * 桃花传音-接收语音
     *
     * @return List<PeachblossomVo>
     */
    public PeachblossomVo acceptPeachblossom() {
        Long currendUserId = UserHolder.getUserId();
        // 1. 使用次数校验
        PeachblossomVo peachblossomVo = new PeachblossomVo();
        String peachblossomKey = "ACCEPT_PEACHBLOSSOM_HASHKEY_" + currendUserId;
        String peachblossomCount = stringRedisTemplate.opsForValue().get(peachblossomKey);
        Integer num = 0;
        if (StringUtils.isNotEmpty(peachblossomCount)){
            num = Integer.valueOf(peachblossomCount);
            if (num == 1){
                peachblossomVo.setRemainingTimes(0);
            } else if (num >= 3 || num < 0){
                throw new SoulGlobalException("桃花语音已达3次数，请明天继续使用！");
            }
        }
        // 2.从语音库随机获取一个桃花传音用户(大数据系统随机匹配一个桃花传音用户并且有语音)
        Peachblossom peachblossom = peachblossomApi.findByPeachblossom(currendUserId);
        if (peachblossom == null){
            return null;
        }
        // 3. 查询桃花传音用户详细信息
        UserInfo userInfo = userInfoApi.findByUserIdUser(peachblossom.getUserId());
        // 4. 构造vo参数
        BeanUtils.copyProperties(peachblossom,peachblossomVo);
        BeanUtils.copyProperties(userInfo,peachblossomVo);
        peachblossomVo.setSoundUrl(peachblossom.getSoundFileUrl());
        // 5. 桃花传音剩余次数
        ++num;
        stringRedisTemplate.opsForValue().set(peachblossomKey,String.valueOf(num));
        if (num == 1){
            peachblossomVo.setRemainingTimes(3);
        } else if (num == 2){
            peachblossomVo.setRemainingTimes(2);
        } else {
            peachblossomVo.setRemainingTimes(1);
        }
        System.err.println("接收桃花传音：" +peachblossomVo);
        return peachblossomVo;
    }
}
